<?php
class ClsInstall extends ClsNaanalController
{
    public function __construct()
    {
        parent::__construct();
    }
    protected function getContent($directory,$name)
    {
        if($directory=="modules/install/")
        {
            return $this->getAppInstallModuleContent($name);
        }
        else
        {
            if($name=="inner.php")
            {
                $content='<?php
echo $out;
?>';
                return $content;
            }
            if($name=="common.php")
            {
                $common_php='<?php
$lang=array
(
    "HelloWorld"=>"Hello World!!!"
);
?>';
            return $common_php;
            }
            else if($name=="err.ini")
            {
                return "LOGIN_ERROR=Unknown UserID or Password";
            }
            else
            {
                return '<?php
?>';
            }
        }
    }
    protected function getAppInstallModuleContent($name)
    {
        if($name=="config.php")
        {
            return '<?php
$is_authentication_needed=false; 
$database=true;
$table=false;
$control_panel=true;
$theme="default";
$actions=array();
$template_variables=array();
$template_function_calls=array();
?>';
        }
        else if($name=="create.php")
        {
            return '<?php
copy("config.default.php","config.php");
?>
';
        }
        else if($name=="ClsInstall.php")
        {
            return '<?php
include_once(\'./modules/install/Schema.php\');

class ClsInstall extends ClsNaanalController
{
    public function __construct()
    {
        parent::__construct();

        $this->_authenticationRequired = false;
        $this->_moduleDirectory = \'install\';
        $this->_moduleName = \'install\';
        $this->_schema = $this->getSchema();
    }
    public function getSchema()
    {
        $schema=null;
        if(file_exists("modules/install/schema.php"))
        {
            include "modules/install/schema.php";
        }
        return $schema;
    }
    public function handleRequest()
    {
    }
}

?>
';
        }
        else if($name=="schema.php")
        {
            return '<?php
?>';
        }
    }
    protected function createDefaultFiles()
    {
        $arrDirectory=array();
        $arrFile=array();
        
        //directory : gate
        $arrDirectory[]="gate/";
        $arrDirectory[]="gate/default/";
        $arrFile[]=array
        (
            "directory"=>"gate/default/",
            "name"=>"entry.php"
        );
        $arrFile[]=array
        (
            "directory"=>"gate/default/",
            "name"=>"exit.php"
        );
        //end
        
        //directory : lang
        $arrDirectory[]="lang/";
        $arrDirectory[]="lang/default/";
        $arrFile[]=array
        (
            "directory"=>"lang/default/",
            "name"=>"common.php"
        );
        //end
        
        //directory : workplace
        $arrDirectory[]="workplace/";
        $arrDirectory[]="workplace/lang/";
        $arrDirectory[]="workplace/lang/default/";
        $arrFile[]=array
        (
            "directory"=>"workplace/lang/default/",
            "name"=>"common.php"
        );
        //end
        
        //directory : client
        $arrDirectory[]="client/";
        $arrDirectory[]="client/default/";
        //end
        
        //directory : .
        $arrFile[]=array
        (
            "directory"=>"./",
            "name"=>"hooks.php"
        );
        $arrFile[]=array
        (
            "directory"=>"./",
            "name"=>"err.ini"
        );
        $arrFile[]=array
        (
            "directory"=>"./",
            "name"=>"config.default.php"
        );
        //
        
        //directory : themes
        $arrDirectory[]="themes/";
        $arrDirectory[]="themes/default/";
        $arrFile[]=array
        (
            "directory"=>"themes/default/",
            "name"=>"inner.php"
        );
        
        $arrDirectory[]="log/";
        
        //directory : install
        $arrDirectory[]="modules/";
        $arrDirectory[]="modules/install/";
        $arrDirectory[]="modules/install/lang/";
        $arrDirectory[]="modules/install/lang/default/";
        $arrFile[]=array
        (
            "directory"=>"modules/install/",
            "name"=>"ClsInstall.php"
        );
        $arrFile[]=array
        (
            "directory"=>"modules/install/",
            "name"=>"create.php"
        );
        $arrFile[]=array
        (
            "directory"=>"modules/install/",
            "name"=>"config.php"
        );
        $arrFile[]=array
        (
            "directory"=>"modules/install/lang/default/",
            "name"=>"common.php"
        );
        $arrFile[]=array
        (
            "directory"=>"modules/install/",
            "name"=>"schema.php"
        );
        //end
        
        
        foreach($arrDirectory as $directory)
        {
            if(!file_exists($directory)) mkdir($directory);
        }
        
        foreach($arrFile as $file)
        {
            if(!file_exists("{$file["directory"]}{$file["name"]}")) file_put_contents("{$file["directory"]}{$file["name"]}",$this->getContent($file["directory"], $file["name"]));
        }
    }
    public function getAppConfigContent()
    {
        $objRequest=ClsNaanalRequest::getInstance();
        $databaseConfigType=$objRequest->getData("database_config_type");
        $configvars=$objRequest->getData("configvars");
        $arrDatabaseVars=$objRequest->getData("database");
        $create_default_directory=$objRequest->getData("create_default_directory");
        $loginTable=$objRequest->getData("login_table");
        $homePage=$objRequest->getData("home_page");
        $homeAction=$objRequest->getData("home_action");
        $loginPage=$objRequest->getData("login_page");
        $loginAction=$objRequest->getData("login_action");
        $logoutPage=$objRequest->getData("logout_page");
        $logoutAction=$objRequest->getData("logout_action");
        
        $controlPanel=$objRequest->getData("control_panel");
        
        $enableLog=$objRequest->getData("enable_log")?"true":"false";
        $enableLang=$objRequest->getData("enable_lang")?"true":"false";
        $isDeveloperMode=$objRequest->getData("is_developer_mode")?"true":"false";
        $enableTracking=$objRequest->getData("enable_tracking")?"false":"true";
        $theme=$objRequest->getData("theme")?$objRequest->getData("theme"):"default";
        
        $arrStaticVar=array();
        $arrStaticVar["DATABASE_CONFIG_TYPE"]=$databaseConfigType;
        $arrStaticVar["DATABASE"]='';
        $arrStaticVar["ALLOWED_TEMPLATE_TOKEN"]='';
        $arrStaticVar["SESSION_NAME"]='';
        $arrStaticVar["DATABASE_WRAPPER_CLASS"]='';
        $arrStaticVar["CONFIG_VAR_MAP"]='';
        $arrStaticVar["CONFIG_VAR"]='';
        $arrStaticVar["URL_MODULE_PARAM"]='';
        $arrStaticVar["URL_ACTION_PARAM"]='';
        $arrStaticVar["FLD_USERID"]='';
        $arrStaticVar["CONTROL_PANEL"]='';
        $arrStaticVar["LOG"]='';
        $arrStaticVar["LANG"]='';
        $arrStaticVar["isDeveloperMode"]='';
        $arrStaticVar["DISABLE_TRACKING"]='';
        $arrStaticVar["theme"]='';
    }
    public function loadConfigFile($arrPrepareVar)
    {
        $content="";
        if(!empty($arrPrepareVar))
        {
            foreach($arrPrepareVar as $arrVar)
            {
                if($arrVar["type"]=="constant")
                {
                    $content=$content."define('{$arrVar["variable"]}','{$arrVar["data"]}');\n";
                }
                else
                {
                    $content=$content."\${$arrVar["variable"]}='{$arrVar["data"]}';\n";
                }
            }
        }
        $success=file_put_contents("config.default.php",'<?php
'.$content.'
?>');
        if(!$success)
        {
            die("unable to write config.default.php");
        }
    }
    public function prepareConfigVar($configvars)
    {
        $arrPrepareVar=array();$configvars=stripslashes($configvars);
        $configvars=trim($configvars);
        if(!empty($configvars))
        {
            $arrConfigVar=explode(",",$configvars);
            foreach($arrConfigVar as $var)
            {
                $matches=array();
                $arrVar=  preg_match("/([a-zA-Z_\]\[\'\"\s]+):([a-zA-Z_\]\[\'\"\s]+)=([a-zA-Z_\]\[\'\"\s]+)/", $var,$matches);
                $confVar=isset($matches[1])?$matches[1]:null;
                $confType=isset($matches[2])?$matches[2]:null;
                $confData=isset($matches[3])?$matches[3]:null;
                //$arrVar=explode(":",$var);
                if(is_null($confType))
                {
                    die("colon not exist in config var($var) in ($configvars)");
                }
                $arr=array();
                $arr["variable"]=$confVar;
                $arr["type"]=$confType;
                $arr["data"]=$confData;
                $arrPrepareVar[]=$arr;
            }
        }
        return $arrPrepareVar;
    }
    public function onCreate()
    {
        $objRequest=ClsNaanalRequest::getInstance();
        $databaseConfigType=$objRequest->getData("database_config_type");
        $arrDatabaseVars=$objRequest->getData("database");
        $create_default_directory=$objRequest->getData("create_default_directory");
        $loginTable=$objRequest->getData("login_table");
        $homePage=$objRequest->getData("home_page");
        $homeAction=$objRequest->getData("home_action");
        $loginPage=$objRequest->getData("login_page");
        $loginAction=$objRequest->getData("login_action");
        $logoutPage=$objRequest->getData("logout_page");
        $logoutAction=$objRequest->getData("logout_action");
        
        $controlPanel=$objRequest->getData("control_panel");
        
        $enableLog=$objRequest->getData("enable_log")?"true":"false";
        $enableLang=$objRequest->getData("enable_lang")?"true":"false";
        $isDeveloperMode=$objRequest->getData("is_developer_mode")?"true":"false";
        $enableTracking=$objRequest->getData("enable_tracking")?"false":"true";
        $theme=$objRequest->getData("theme")?$objRequest->getData("theme"):"default";
        
        if($create_default_directory)
        {
            $this->createDefaultFiles();
        }
        $configvars=$objRequest->getData("configvars");
        $arrPrepareVar=$this->prepareConfigVar($configvars);
        $arrTmpConfigVar=array();
        if($arrDatabaseVars)
        foreach($arrDatabaseVars as $k=>$v)
        {
            $arrTmpConfigVar[]=array("variable"=>$v,"data"=>'['.$v.']',"type"=>$databaseConfigType);
        }
        if($arrPrepareVar)
        foreach($arrPrepareVar as $arrVar)
        {
            $arrTmpConfigVar[]=$arrVar;
        }
        $this->loadConfigFile($arrTmpConfigVar);
        $arrConfigVar=array();
        $arrConfigVar=explode(",",$configvars);
        $staticConfigVar="";
        if(!empty($arrDatabaseVars))
        foreach($arrDatabaseVars as $k=>$var)
        {
            $trimVar=trim($var);
            if(empty($trimVar)) continue;
            if(empty($staticConfigVar))
            {
                $staticConfigVar=$staticConfigVar."'$k'=>'{$trimVar}'";
            }
            else
            {
                $staticConfigVar=$staticConfigVar.",'$k'=>'{$trimVar}'";
            }
        }
        if(!empty($arrConfigVar))
        foreach($arrConfigVar as $ind=>$var)
        {
            $trimVar=trim($var);
            if(empty($trimVar)) continue;
            if(empty($staticConfigVar))
            {
                $staticConfigVar=$staticConfigVar."'{$trimVar}'";
            }
            else
            {
                $staticConfigVar=$staticConfigVar.",'{$trimVar}'";
            }
        }
        $configStaticVars=$staticConfigVar;
        $configControlPanel="";
        if(empty($controlPanel))
        {
            $configControlPanel='array()';
        }
        else
        {
            $configControlPanel="array
(
    '{$controlPanel}'=>array
    (
        'database'=>'{$arrDatabaseVars["DATABASE_NAME"]}',
        'table'=>array
        (
            'login'=>'{$loginTable}'
        ),
        'page'=>array
        (
            'home'=>array
            (
                'module'=>'{$homePage}',
                'action'=>'{$homeAction}'
            ),
            'login'=>array
            (
                'module'=>'{$loginPage}',
                'action'=>'{$loginAction}'
            ),
            'logout'=>array
            (
                'module'=>'{$logoutPage}',
                'action'=>'{$logoutAction}'
            )
        )
    )
)";
        }
        
        file_put_contents("ClsConfig.php", '<?php
define("DEVELOPER_IP","127.0.0.1");
class ClsConfig
{
    static $DATABASE_CONFIG_TYPE="'.$databaseConfigType.'";
    static $DATABASE=array();
    static $CONFIG_VAR_MAP=array('.$configStaticVars.');
    static $CONFIG_VAR=array();
    static $CONFIG_MANDATORY_VAR=array();
    static $CONFIG_FILE="config.php";
    static $WORKPLACE_PATH="workplace/";
    static $CONTROL_PANEL='.$configControlPanel.';
    static $LOG='.$enableLog.';
    static $LANG='.$enableLang.';
    static $isDeveloperMode='.$isDeveloperMode.';
    static $DISABLE_TRACKING='.$enableTracking.';
    static $theme="'.$theme.'";
}
?>');
        if(!$this->isModuleExist("home"))
        {
            $this->createEmptyModule("home");
        }
        $this->redirect="module=home";
    }
    public function isModuleExist($name)
    {
        if(file_exists("modules/{$name}"))
        {
           return true; 
        }
        return false;
    }
    public function createEmptyModule($name)
    {
        if(!file_exists("modules/{$name}"))
        {
            mkdir("modules/{$name}/lang/default", 0777, true);
            $uname=ucfirst($name);
            file_put_contents("modules/{$name}/Cls{$uname}.php", "<?php
class Cls{$uname} extends ClsNaanalController
{
    public function __construct()
    {
        parent::__construct();
    }
}
?>");
            file_put_contents("modules/{$name}/ClsW{$uname}.php", "<?php
class ClsW{$uname} extends ClsWrapper
{
    public function __construct()
    {
        parent::__construct();
    }
}
?>");
            file_put_contents("modules/{$name}/{$name}.php", "<?php
echo 'Hello World!!!';
?>");
            file_put_contents("modules/{$name}/lang/default/common.php", "<?php
?>");
            file_put_contents("modules/{$name}/config.php", "<?php
\$is_authentication_needed=false;
\$control_panel=false;
\$database=false;
\$table=false;
\$theme=true;
\$actions=array();
\$template_variables=array();
\$template_function_calls=array();
\$fields=array();
?>");
        }
    }
    public function create()
    {
        
    }
    public function insert()
    {
        
    }
}
?>